package screen;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import weibo.Friendships;
import weibo.http.AccessToken;
//import weibo.model.Oauth2AccessToken;
import weibo.model.Status;
import weibo.model.User;
import weibo.model.UserWapper;
import weibo.model.WeiboException;
import code.Config;
import code.Function;
import ctrl.ForegroundManager;
import ctrl.ListStyleButtonSet;
import ctrl.UserInforListStyleButtonField;

public class ShowFriendsScreen extends MainScreen
{
	//Oauth2AccessToken _accessToken;
	AccessToken _accessToken;
	String _uid;
	User _user;
	UserWapper _users;
	
	String _screen_name;
	int _screen_type;
	ForegroundManager _foreground=new ForegroundManager(0);
	ListStyleButtonSet _buttonSet=new ListStyleButtonSet();
	UserInforListStyleButtonField link;
	Status status=null;
	byte[] avatarData=null;
	
    ConnectionThread _connectionThread = new ConnectionThread();
	
	public ShowFriendsScreen(AccessToken accessToken, String screen_name, String uid, int screen_type)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | VERTICAL_SCROLLBAR);
		
        if(!_connectionThread.isStarted()) {_connectionThread.start();}
        
		_accessToken=accessToken;
		_uid=uid;
		_screen_name=screen_name;
		_screen_type=screen_type;
	
		HorizontalFieldManager hfm=new HorizontalFieldManager(FIELD_HCENTER);
		if(_screen_type==Config.SCREEN_TYPE_FRIENDS)
		{
			hfm.add(new LabelField(_screen_name+"的关注列表"));
		} else {
			hfm.add(new LabelField(_screen_name+"的粉丝列表"));
		}
		setTitle(hfm);
		
		_buttonSet.add(new LabelField("Please wait....", USE_ALL_WIDTH));
		_foreground.add(_buttonSet);
		
		add(_foreground);
		
		_connectionThread.fetch();	
	}
	
	public ShowFriendsScreen(AccessToken accessToken, User user, int screen_type)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT);
		
        if(!_connectionThread.isStarted()) {_connectionThread.start();}
        
		_accessToken=accessToken;
		_user=user;
		_uid=_user.getId();
		_screen_type=screen_type;
	
		HorizontalFieldManager hfm=new HorizontalFieldManager(FIELD_HCENTER);
		if(_screen_type==Config.SCREEN_TYPE_FRIENDS)
		{
			hfm.add(new LabelField(_user.getScreenName()+"的关注列表"));
		} else {
			hfm.add(new LabelField(_user.getScreenName()+"的粉丝列表"));
		}
		setTitle(hfm);
		
		_buttonSet.add(new LabelField("Please wait....", USE_ALL_WIDTH));
		_foreground.add(_buttonSet);
		
		add(_foreground);
		
		_connectionThread.fetch();	
	}
	
	public boolean onClose()
	{
		_connectionThread.stop();
		
		return super.onClose();
	}
	
	class ConnectionThread extends Thread
    {
        private static final int TIMEOUT = 500;
        
        private volatile boolean _fetchStarted = false;
        private volatile boolean _stop = false;

        private String getAccessToken() {return _accessToken.getToken();}
        
        private boolean isStarted() {return _fetchStarted;}            
     
        private void fetch() {_fetchStarted = true;}

        private void stop() {_stop = true;}

        public void run()
        {
            for(;;)
            {
                while( !_fetchStarted && !_stop)  
                {
                    try 
                    {
                        sleep(TIMEOUT);
                    } 
                    catch (InterruptedException e) {Function.errorDialog("Thread#sleep(long) threw " + e.toString());}
                }
                
                if(_stop) {return;}
                
				Friendships fm=new Friendships(getAccessToken());

				try {
					if(_screen_type==Config.SCREEN_TYPE_FRIENDS)
					{
						_users = fm.getFriendsByID(_uid);
					} else {
						_users=fm.getFollowersById(_uid);
					}

					synchronized(UiApplication.getEventLock())
					{
						UiApplication.getUiApplication().invokeLater(new Runnable()
						{
							public void run()
							{
								for(int i=0; i<_users.getUsers().size(); i++)
								{
									_user=(User) _users.getUsers().elementAt(i);
									status=_user.getStatus();
									
									final String uid=_user.getId();
									link=new UserInforListStyleButtonField(_user);
									link.setChangeListener(new FieldChangeListener()
									{
										public void fieldChanged(Field field, int context) 
										{
											UiApplication.getUiApplication().pushModalScreen(new UserInformationScreen(_accessToken, uid));
											//UiApplication.getUiApplication().pushModalScreen(new UserInformationScreen(_accessToken, _user));
										}
									});
									_buttonSet.add(link);
								}
							}
						});
					}

					UiApplication.getUiApplication().invokeLater(new Runnable()
					{
						public void run()
						{
							if(_buttonSet.getField(0) instanceof LabelField) {_buttonSet.delete(_buttonSet.getField(0));}	
							if(_users.getUsers().size()==0) {UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());}
						}
					});
				} catch (WeiboException e) {Function.errorDialog(e.toString());}
				
	            _fetchStarted = false;     
	            //stop();
			}
        }
    }
}